package com.cjg.shadowhostpro.ipc;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.cjg.common_lib.IClientCallback;
import com.cjg.common_lib.IRemoteService;

import java.util.ArrayList;
import java.util.List;

public class RemoteService extends Service {
    private static final String TAG = "RemoteService";

    // 存储所有注册的客户端回调
    private final List<IClientCallback> mCallbacks = new ArrayList<>();

    // Binder 实现，返回 IRemoteService 接口的具体实现
    private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
        @Override
        public void registerCallback(IClientCallback callback) throws RemoteException {
            if (callback != null && !mCallbacks.contains(callback)) {
                mCallbacks.add(callback);
                Log.d(TAG, "Client callback registered");
            }
        }

        @Override
        public void unregisterCallback(IClientCallback callback) throws RemoteException {
            mCallbacks.remove(callback);
            Log.d(TAG, "Client callback unregistered");
        }

        @Override
        public void sendMessageToService(String message) throws RemoteException {
            Log.d(TAG, "Received from client: " + message);

            // 处理消息后，向所有客户端发送回复
//            sendMessageToAllClients("Server received: " + message);
        }

        @Override
        public void sendMessageToClient(String message) throws RemoteException {
            Log.d(TAG, "Received from client: " + message);
            List<IClientCallback> callbacks = new ArrayList<>(mCallbacks);
            for (IClientCallback callback : callbacks) {
                try {
                    callback.onMessageFromService(message);
                } catch (RemoteException e) {
                    Log.e(TAG, "Error sending message to client", e);
                    // 移除失效的回调
                    mCallbacks.remove(callback);
                }
            }
            // 处理消息后，向所有客户端发送回复
//            sendMessageToAllClients("Server received: " + message);
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
}